#!/bin/bash
# Go和Node.js安装与环境配置整合脚本
# 此脚本整合了之前所有脚本的最佳实践，提供完整的Go和Node.js安装与环境配置方案
# 使用说明：在项目根目录下运行此脚本

# 配置参数
PROJECT_DIR="$(pwd)"
VENV_NAME="lzy-xiuxian"
GO_VERSION="1.25.1"
NODE_VERSION="22.19.0"

# 创建临时目录
PROJECT_TEMP_DIR="$PROJECT_DIR/tmp"
mkdir -p "$PROJECT_TEMP_DIR"

# 函数：检查命令是否存在
has_command() {
    command -v "$1" > /dev/null 2>&1
}

# 函数：显示进度条
show_progress() {
    local duration=$1
    local message=$2
    local progress=0
    local total_steps=10
    local step_duration=$((duration / total_steps))
    
    echo -n "$message: ["
    
    while [ $progress -lt $total_steps ]; do
        echo -n "="
        progress=$((progress + 1))
        sleep $step_duration
    done
    
    echo "] 完成"
}

# 函数：显示成功信息
echo_success() {
    echo -e "\033[0;32m$1\033[0m"
}

# 函数：显示错误信息
echo_error() {
    echo -e "\033[0;31m$1\033[0m"
}

# 函数：显示警告信息
echo_warning() {
    echo -e "\033[0;33m$1\033[0m"
}

# 检查并激活虚拟环境
check_conda_env() {
    echo "=== 检查虚拟环境 ==="
    
    if ! has_command "conda"; then
        echo_error "错误：未找到conda命令，请先安装Anaconda或Miniconda"
        exit 1
    fi
    
    # 检查虚拟环境是否存在
    if conda env list | grep -q "$VENV_NAME"; then
        echo_success "✓ 虚拟环境 $VENV_NAME 已存在"
    else
        echo_warning "警告：虚拟环境 $VENV_NAME 不存在，正在创建..."
        conda create -n "$VENV_NAME" python=3.9 -y
        if [ $? -ne 0 ]; then
            echo_error "错误：创建虚拟环境失败"
            exit 1
        fi
        echo_success "✓ 虚拟环境 $VENV_NAME 创建成功"
    fi
    
    # 检查是否已激活虚拟环境
    if [ "$CONDA_DEFAULT_ENV" != "$VENV_NAME" ]; then
        echo_warning "警告：当前未激活目标虚拟环境，请手动激活："
        echo_warning "    conda activate $VENV_NAME"
        echo_warning "然后重新运行此脚本"
        exit 1
    fi
    
    VENV_PATH="$CONDA_PREFIX"
    echo_success "✓ 已成功激活虚拟环境：$VENV_PATH"
}

# 安装Node.js
install_nodejs() {
    echo "\n=== 安装Node.js ==="
    
    if has_command "node" && node --version | grep -q "v$NODE_VERSION"; then
        echo_success "✓ Node.js v$NODE_VERSION 已安装"
        return 0
    fi
    
    echo "正在安装Node.js v$NODE_VERSION..."
    conda install -c conda-forge nodejs="$NODE_VERSION" -y
    
    if [ $? -ne 0 ]; then
        echo_error "错误：Node.js安装失败"
        return 1
    fi
    
    # 配置npm全局包路径
    NPM_GLOBAL_PATH="$VENV_PATH/npm-global"
    mkdir -p "$NPM_GLOBAL_PATH"
    npm config set prefix "$NPM_GLOBAL_PATH"
    
    echo_success "✓ Node.js v$NODE_VERSION 安装成功"
    echo_success "✓ npm全局包路径已配置为：$NPM_GLOBAL_PATH"
    return 0
}

# 使用国内镜像源安装Go
install_go() {
    echo "\n=== 安装Go ==="
    
    GO_INSTALL_PATH="$VENV_PATH/go"
    GO_BIN_PATH="$GO_INSTALL_PATH/bin"
    
    # 检查Go是否已安装且版本正确
    if [ -f "$GO_BIN_PATH/go" ] && "$GO_BIN_PATH/go" version | grep -q "go$GO_VERSION"; then
        echo_success "✓ Go $GO_VERSION 已安装在 $GO_INSTALL_PATH"
        return 0
    fi
    
    # 确定系统架构
    ARCH=$(uname -m)
    case $ARCH in
        x86_64) GO_ARCH="amd64" ;;
        aarch64) GO_ARCH="arm64" ;;
        *) 
            echo_error "错误：不支持的系统架构：$ARCH"
            return 1
            ;;
    esac
    
    # 设置下载文件名和路径
    GO_FILENAME="go$GO_VERSION.linux-$GO_ARCH.tar.gz"
    GO_DOWNLOAD_URL="https://golang.google.cn/dl/$GO_FILENAME"
    
    echo "正在从国内镜像源下载Go $GO_VERSION..."
    if ! wget -O "$PROJECT_TEMP_DIR/$GO_FILENAME" "$GO_DOWNLOAD_URL" --progress=bar:force 2>&1; then
        # 尝试备用镜像源
        echo_warning "警告：主镜像源下载失败，尝试备用镜像源..."
        GO_DOWNLOAD_URL="https://mirrors.aliyun.com/golang/$GO_FILENAME"
        if ! wget -O "$PROJECT_TEMP_DIR/$GO_FILENAME" "$GO_DOWNLOAD_URL" --progress=bar:force 2>&1; then
            echo_error "错误：所有镜像源下载都失败了"
            return 1
        fi
    fi
    
    # 解压安装
    echo "正在解压并安装Go..."
    rm -rf "$GO_INSTALL_PATH"
    mkdir -p "$GO_INSTALL_PATH"
    tar -C "$GO_INSTALL_PATH" --strip-components=1 -xzf "$PROJECT_TEMP_DIR/$GO_FILENAME"
    
    if [ $? -ne 0 ]; then
        echo_error "错误：Go安装失败"
        return 1
    fi
    
    echo_success "✓ Go $GO_VERSION 安装成功"
    echo_success "✓ Go安装路径：$GO_INSTALL_PATH"
    return 0
}

# 配置环境变量（使用Conda激活脚本机制）
configure_environment() {
    echo "\n=== 配置环境变量 ==="
    
    GO_INSTALL_PATH="$VENV_PATH/go"
    GO_BIN_PATH="$GO_INSTALL_PATH/bin"
    GO_PKG_PATH="$GO_INSTALL_PATH/pkg"
    NPM_GLOBAL_PATH="$VENV_PATH/npm-global"
    
    # 创建Conda激活和停用脚本目录
    mkdir -p "$VENV_PATH/etc/conda/activate.d"
    mkdir -p "$VENV_PATH/etc/conda/deactivate.d"
    
    # 创建激活脚本
    ACTIVATE_SCRIPT="$VENV_PATH/etc/conda/activate.d/go_vars.sh"
    echo "创建激活脚本: $ACTIVATE_SCRIPT"
    cat > "$ACTIVATE_SCRIPT" << 'EOF'
#!/bin/bash

# 虚拟环境和Go安装路径
VENV_PATH="$CONDA_PREFIX"
GO_INSTALL_PATH="$VENV_PATH/go"
GO_BIN_PATH="$GO_INSTALL_PATH/bin"
GO_PKG_PATH="$GO_INSTALL_PATH/pkg"
NPM_GLOBAL_PATH="$VENV_PATH/npm-global"

# 设置Go环境变量
export GOROOT="$GO_INSTALL_PATH"
export GOPATH="$GO_PKG_PATH"

# 将Go的bin目录和npm全局包路径添加到PATH
export PATH="$GO_BIN_PATH:$GO_PKG_PATH/bin:$NPM_GLOBAL_PATH/bin:$PATH"

# 创建必要的目录
mkdir -p "$GO_PKG_PATH" &> /dev/null
mkdir -p "$NPM_GLOBAL_PATH" &> /dev/null

EOF
    
    # 为激活脚本添加执行权限
    chmod +x "$ACTIVATE_SCRIPT"
    
    # 创建停用脚本
    DEACTIVATE_SCRIPT="$VENV_PATH/etc/conda/deactivate.d/go_vars.sh"
    echo "创建停用脚本: $DEACTIVATE_SCRIPT"
    cat > "$DEACTIVATE_SCRIPT" << 'EOF'
#!/bin/bash

# 清除Go环境变量
unset GOROOT
unset GOPATH

# 注意：不需要手动修改PATH，Conda会自动处理PATH的恢复
EOF
    
    # 为停用脚本添加执行权限
    chmod +x "$DEACTIVATE_SCRIPT"
    
    echo_success "✓ 环境变量配置脚本创建成功"
}

# 验证安装
verify_installation() {
    echo "\n=== 验证安装 ==="
    
    # 创建临时测试脚本
    TEST_SCRIPT="$PROJECT_TEMP_DIR/test_env.sh"
    cat > "$TEST_SCRIPT" << 'EOF'
#!/bin/bash

# 临时验证脚本
echo "=== 环境变量验证 ==="
echo "GOROOT: $GOROOT"
echo "GOPATH: $GOPATH"
echo "PATH包含Go: $(echo $PATH | grep -q "$GOROOT/bin" && echo "是" || echo "否")"
echo "PATH包含npm全局: $(echo $PATH | grep -q "$NPM_GLOBAL_PATH/bin" && echo "是" || echo "否")"
echo ""
echo "=== 命令验证 ==="
echo -n "Go版本: "
if command -v go &> /dev/null; then
    go version
else
    echo "未找到"
fiecho -n "Node.js版本: "
if command -v node &> /dev/null; then
    node --version
else
    echo "未找到"
fiecho -n "npm版本: "
if command -v npm &> /dev/null; then
    npm --version
else
    echo "未找到"
fi
EOF
    
    chmod +x "$TEST_SCRIPT"
    
    echo "注意：要完全验证配置，您需要停用并重新激活虚拟环境"
    echo_success "\n安装与配置总结："
    echo_success "1. ✓ 虚拟环境已检查并激活"
    echo_success "2. ✓ Node.js v$NODE_VERSION 已安装"
    echo_success "3. ✓ Go $GO_VERSION 已使用国内镜像源安装"
    echo_success "4. ✓ 环境变量配置已完成（使用Conda激活脚本机制）"
    echo ""
    echo_warning "使用说明："
    echo_warning "1. 停用并重新激活虚拟环境以应用配置："
    echo_warning "   conda deactivate"
    echo_warning "   conda activate $VENV_NAME"
    echo_warning "2. 激活后，您可以直接使用Go、Node.js和npm命令"
    echo_warning "3. 这些环境变量只会在激活虚拟环境时生效，实现了与系统的完全隔离"
    echo ""
    echo_success "环境安装与配置已成功完成！"
}

# 清理临时文件
cleanup() {
    echo "\n=== 清理临时文件 ==="
    if [ -d "$PROJECT_TEMP_DIR" ]; then
        rm -rf "$PROJECT_TEMP_DIR"
        echo_success "✓ 临时文件已清理"
    fi
}

# 主流程
echo "================================================="
echo_success "开始Go和Node.js安装与环境配置..."
echo "项目目录: $PROJECT_DIR"
echo "目标虚拟环境: $VENV_NAME"
echo "================================================="

check_conda_env
if [ $? -ne 0 ]; then
    echo_error "虚拟环境检查失败，脚本终止"
    exit 1
fi

install_nodejs
if [ $? -ne 0 ]; then
    echo_error "Node.js安装失败，脚本终止"
    exit 1
fi

install_go
if [ $? -ne 0 ]; then
    echo_error "Go安装失败，脚本终止"
    exit 1
fi

configure_environment
verify_installation
cleanup

echo "\n================================================="
echo_success "所有操作已成功完成！祝您开发愉快！"
echo "================================================="